//
//  AppendVC.swift
//  HLDesktop
//
//  Created by 黄龙 on 2023/8/29.
//

import UIKit

class AppendVC: UIViewController {

    let tableView:UITableView = {
        let table = UITableView()
        return table
    }()
    
    lazy var workAreaView: UIView = {
        let sView = UIView()
        return sView
    }()
    
    var souSuoView:UIView?
    var customDefineView:UIView?
    var customImgLogo:UIImageView?
    var customLogoName:String? //选择的图标url
    var customFieldName:UITextField?
    var customFieldCmd:UITextField?
    var customExampleLabel = ActiveLabel() //举例说明
    
    let jsonfiles:[String] = ["mostuse_apps","zifuplay_apps","hot_apps","config_apps","jiaotong_apps","home_apps",
                              "caijing_apps","youxi_apps","",""]
    var sourceList:[String] = [] //可添加的启动项列表
    var iTabIndex = -1
    var tabItems:[UIButton]=[]
    
    var popMenu:HLPopMenu?
    
    var telPhoneNum:String?
    var telInputDlg:UIView?
    
    var sousuoSource:[[String]] = [] //搜索结果,二维[[本地搜索结果],[AppStore结果]]
    var sousouTitles:[String] = []   //section Title
    var isSousuoPage:Bool = false
    
    public var didAddAppBlock:((_ appData:String)->Void)?
    public var didCloseBlock:((_ snapshot:UIImage?)->Void)? //os_block_t?
    
    let cellHeight = 60.0
    
    var superSnapshotView:UIView?
    var superSnapshotPosition:CGPoint?
    
    deinit {
        print("没有循环引用才会触发:AppendVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemGroupedBackground
        // Do any additional setup after loading the view.
        initView()
        let tapView = UITapGestureRecognizer(target: self, action: #selector(tapBackView))
        tapView.cancelsTouchesInView = false
        tapView.delaysTouchesBegan = false
        tapView.delaysTouchesEnded = false
        view.addGestureRecognizer(tapView)
        
//        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeToRight(_:)))
//        swipeRight.direction = .right
//        view.addGestureRecognizer(swipeRight)
        if let snapView = superSnapshotView{
            snapView.frame = CGRect(x: 0, y: 0, width: screen_W, height: screen_H)
            self.view.addSubview(snapView)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if let _ = superSnapshotView, let position = superSnapshotPosition{
            self.view.animateCircular(withDuration: 0.5, center: position) {
                self.superSnapshotView?.removeFromSuperview()
            }
        }
        UIView.animate(withDuration: 0.25, delay: 0.25,options: [.curveEaseInOut]) {[weak self] in
            if let self = self{
                self.tableView.frame = CGRect(x: 0, y: 0, width: self.workAreaView.bounds.width, height: self.workAreaView.bounds.height)
            }
        }
        let lastIndex = UserDefaults.standard.integer(forKey: "aiScreen.dCache.last.Append.TabIndex")//integerforkey，没有此key时，默认为0
        showPage(ipage: lastIndex)

    }
    
    @objc func tapBackView(){
        view.endEditing(true)
    }
    
//    @objc func swipeToRight(_ recognizer:UISwipeGestureRecognizer){
//        let point=recognizer.location(in: self.view)
////        print(point.x)//这个点是滑动的起点
//        if point.x<20{
//            self.dismiss(animated: true)
//        }
//    }
    
    func initTopBar(_ topSpace:CGFloat){
        let topView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: topSpace))
        view.addSubview(topView)
        let lineH = CALayer()
        topView.layer.addSublayer(lineH)
        lineH.frame = CGRect(x: 0, y: topSpace-0.5, width: screen_W, height: 0.5)
        lineH.backgroundColor = UIColor.systemGray.withAlphaComponent(0.5).cgColor
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: topSpace - 48, width: screen_W, height: 48))
        topView.addSubview(titleLabel)
        titleLabel.font = .boldSystemFont(ofSize: 16)
        titleLabel.text = "添加快捷启动"
        titleLabel.textColor = .label
        titleLabel.textAlignment = .center
        
        let closeButton = UIButton(frame: CGRect(x: screen_W-48, y: topSpace-48, width: 48, height: 48))
        topView.addSubview(closeButton)
        closeButton.setImage(UIImage(named: "toolbar_close_1@2x.png"), for: .normal)
        closeButton.addActionWithBlock {[weak self] (sender) in
            Vibrations.light.vibrate()
            if let theSnapshot = self?.view.snapshot2Image(){
                self?.didCloseBlock?(theSnapshot)
            }
//            self?.didCloseBlock = nil //在superVC中引用didCloseBlock时，并未引用本VC或其View，故无须置为nil
            self?.dismiss(animated: false)
        }
        
        let learnBtn = UIButton(frame: CGRect(x: 0, y: topSpace-48, width: 60, height: 48))
        topView.addSubview(learnBtn)
        learnBtn.setTitle("教程", for: .normal)
        learnBtn.setTitleColor(prjTitleColor, for: .normal)
        learnBtn.titleLabel?.font = .systemFont(ofSize: 16)
        learnBtn.addActionWithBlock { sender in
            Vibrations.light.vibrate()
            HLUniversalFunc.openSchemeUrl("https://note.youdao.com/s/BCrLmxnh", nil) //用safari打开
//            let webVC = WebViewController()
//            self.present(webVC, animated: true)
//            webVC.loadUrlStr(urlstr: "https://note.youdao.com/s/BCrLmxnh",title: "我的Ai桌面-使用教程")
        }
    }
    
    func initView(){
//热门、家居、财经、游戏、交通、设置、原生
        let topSpace = UIDevice.ui_navigationFullHeight()
        self.initTopBar(topSpace)
        
        let sousuoBarHeight = 56.0
        let souSuoView = UIView(frame: CGRect(x: 0, y: topSpace, width: screen_W, height: sousuoBarHeight))
        view.addSubview(souSuoView)
        let edtSousuo = UITextField(frame: CGRect(x: 15, y: 10, width: screen_W-30, height: sousuoBarHeight-20))
        souSuoView.addSubview(edtSousuo)
        edtSousuo.layer.cornerRadius = 6
        edtSousuo.backgroundColor = .secondarySystemGroupedBackground
        edtSousuo.font = .systemFont(ofSize: 16)
        edtSousuo.placeholder = "搜索快捷启动项"
        edtSousuo.textColor = .label
        edtSousuo.clearButtonMode = .whileEditing
        edtSousuo.returnKeyType = .search
        edtSousuo.showLeftIcon(UIImage(systemName: "magnifyingglass"), frame: CGRect(x: 0, y: 0, width: 36, height: 36), imageSize: CGSize(width: 24, height: 24))
        edtSousuo.delegate = self
        edtSousuo.tag = 1001


        let leftView = UIView(frame: CGRect(x: 0, y:topSpace+sousuoBarHeight,  width: 50, height: screen_H-topSpace-sousuoBarHeight))
        view.addSubview(leftView)
//
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 50, height: leftView.bounds.height))
        leftView.addSubview(scrollView)
        scrollView.isPagingEnabled = false
        scrollView.isScrollEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false


        var iTop = 10
        let titles = [String(format: "使\n用\n最\n多"),String(format: "🔥\n小\n程\n序"),String(format: "热\n门\n应\n用"),String(format: "系\n统\n原\n生"),String(format: "交\n通\n出\n行"),String(format: "智\n能\n家\n居"),
                      String(format: "理\n\n财"),String(format: "游\n\n戏"),String(format: "自\n定\n义"),String(format: "搜\n索\n结\n果")]
        for i in 0 ..< titles.count{
            let btn_1 = UIButton(frame: CGRect(x: 14, y: iTop, width: 36, height: 70))
            scrollView.addSubview(btn_1)
            btn_1.easyRoundRect(corner: [.topLeft,.bottomLeft], radii: CGSize(width: 10,height: 15))
            btn_1.setTitle(titles[i], for: .normal)
            btn_1.titleLabel?.numberOfLines = 0
            btn_1.titleLabel?.font = .systemFont(ofSize: 12)
            btn_1.setTitleColor(.secondaryLabel, for: .normal)
            btn_1.backgroundColor = .secondarySystemGroupedBackground
            tabItems.append(btn_1)
            btn_1.tag = i+1
            btn_1.addActionWithBlock {[weak self] (sender) in //不用weakself会造成循环引用导致无法deinit
                self?.showPage(ipage: sender.tag-1)
            }
            iTop += 75
        }
        scrollView.contentSize = CGSize(width: 50, height: iTop+10)
//添加自定义tab（里面可以添加自定义网址快捷、支付宝小程序快捷、微信小程序快捷)
        let lineV = CALayer()
        leftView.layer.addSublayer(lineV)
        lineV.frame = CGRect(x: leftView.bounds.width-2, y: 10, width: 2, height: leftView.bounds.height)
        lineV.backgroundColor = UIColor.tertiarySystemGroupedBackground.withAlphaComponent(0.75).cgColor

        view.addSubview(self.workAreaView)
        workAreaView.frame = CGRect(x: 50, y: topSpace+sousuoBarHeight, width: screen_W-50, height: screen_H-topSpace-sousuoBarHeight)
        workAreaView.backgroundColor = .secondarySystemGroupedBackground
        workAreaView.easyRoundRect(corner: [.topLeft,.topRight], radii: CGSize(width: 10, height: 10))

        workAreaView.addSubview(tableView)
        tableView.frame = CGRect(x: 0, y: 0, width: workAreaView.bounds.width, height: 10)
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.separatorStyle = .singleLine //默认即为singleLine
        tableView.register(AppendAppCell.self, forCellReuseIdentifier: "AppendAppCell")
        tableView.backgroundColor = .secondarySystemGroupedBackground //默认是systemBackground

        if let titles = UserDefaults.standard.value(forKey: "aiScreen.dCache.last.Append.sousuoTitles"){
            self.sousouTitles = titles as! [String]
        }else{
            self.sousouTitles.append("请在上面输入关键词搜索 ⇈")
            self.sousouTitles.append("")
        }
        if let sousuoList = UserDefaults.standard.value(forKey: "aiScreen.dCache.last.Append.sousuoList"){
            self.sousuoSource = sousuoList as! [[String]]
        }else{
            self.sousuoSource.append([])
            self.sousuoSource.append([])
        }
    }
    
    
//MARK: - 切换tab
    func showPage(ipage:Int){
        self.view.endEditing(true)
        if iTabIndex == ipage && ipage < tabItems.count - 1 { //搜索页除外
            return
        }else{
            UserDefaults.standard.setValue(ipage, forKey: "aiScreen.dCache.last.Append.TabIndex")
            UserDefaults.standard.synchronize()
        }
        
//先将上一个tab颜色恢复，再将本tab颜色高亮
        if iTabIndex >= 0 && iTabIndex < tabItems.count{
            tabItems[iTabIndex].backgroundColor = .secondarySystemGroupedBackground //.systemGray.withAlphaComponent(0.5)
            UIView.animate(withDuration: 0.15) {
                self.tabItems[self.iTabIndex].titleLabel?.font = .systemFont(ofSize: 12)
            }
            tabItems[iTabIndex].setTitleColor(.secondaryLabel, for: .normal)
        }
        if ipage >= 0 && ipage < tabItems.count{
            UIView.animate(withDuration: 0.25) {
                self.tabItems[ipage].backgroundColor = prjTitleColor.withAlphaComponent(0.5)
            }
            tabItems[ipage].titleLabel?.font = .boldSystemFont(ofSize: 12)
            tabItems[ipage].setTitleColor(.label, for: .normal)
        }
//读取页面数据，然后加载
        iTabIndex = ipage
        let jsonName = jsonfiles[ipage]
      
        souSuoView?.isHidden = true
        customDefineView?.isHidden = true

        sourceList.removeAll()
        isSousuoPage = false
        
        if iTabIndex == tabItems.count - 2{
//自定义cell
            self.initCustomDefineView()
            self.tableView.frame = CGRect(x: 0, y: workAreaView.bounds.height-1, width: workAreaView.bounds.width, height: 1)
        }
        else if iTabIndex == tabItems.count - 1{
//搜索本地及AppStore列表
            isSousuoPage = true
//test:
//            self.sousuoSource.removeAll()
//            self.sousuoSource.append([
//                "url=aqarahome://&|&title=Aqara Home&|&icon=https://a-1251679148.file.myqcloud.com/api/icon/ap3/aqarahome.png",
//                 "url=xiaodiguanjia://&|&title=德施曼智能&|&icon=https://a-1251679148.file.myqcloud.com/api/icon/ap3/xiaodiguanjia.png"])
//            self.sousuoSource.append([
//                "url=mico://&|&title=小爱音箱&|&icon=https://a-1251679148.file.myqcloud.com/api/icon/ap3/xiaoaiyinxiang.png",
//                 "url=haierUplus://&|&title=海尔智家&|&icon=https://a-1251679148.file.myqcloud.com/api/icon/ap3/haierzhijia.png"])
            self.tableView.frame = CGRect(x: 0, y: 0, width: workAreaView.bounds.width, height: workAreaView.bounds.height)
        }
        else{
            self.tableView.frame = CGRect(x: 0, y: 0, width: workAreaView.bounds.width, height: workAreaView.bounds.height)
            sourceList = HLUniversalFunc.getArrFromJSONFile(forName: jsonName)
        }
        self.tableView.reloadData()
    }
    
    func showPopmenu(cellRect:CGRect,at indexPath: IndexPath){
        //数据源（icon可不填）
        var popData = [(icon:"menu_1@2x.png",title:"测试运行"),
                       (icon:"menu_2@2x.png",title:"添加至我的Ai桌面")]
        
        if isSousuoPage{
            let iSec = indexPath.section
            if iSec<sousuoSource.count{
                let row = indexPath.row
                if row < sousuoSource[iSec].count{
                    let content = sousuoSource[iSec][row]
                    let arr = content.components(separatedBy: "&|&")
                    if arr[0].hasPrefix("url=tel://%@"){
                        popData.append((icon:"menu_modi@2x.png",title:"设定要拨打的电话")) //特殊情况
                    }
                }
            }
        }else{
            let row = indexPath.row
            if row < sourceList.count{
                let content = sourceList[row]
                let arr = content.components(separatedBy: "&|&")
                if arr[0].hasPrefix("url=tel://%@"){
                    popData.append((icon:"menu_modi@2x.png",title:"设定要拨打的电话")) //特殊情况
                }
            }
        }
        //设置参数
        let parameters:[HLPopMenuConfigure] = [
            .PopMenuTextColor(.label),
            .popMenuItemHeight(44),
            .PopMenuTextFont(UIFont.systemFont(ofSize: 18))
        ]
        
        
        //init  (test随机生成点位置，注意：arrow点是基于屏幕的位置)
        let cellTop = cellRect.origin.y
        let btnCenterY = cellTop + cellHeight/2.0
        
        popMenu = HLPopMenu(menuWidth: 220, arrow: CGPoint(x: cellRect.width-15-24+50, y: btnCenterY),arrowMargin: 12, datas: popData,configures: parameters)

        //click
//        popMenu.didSelectMenuBlock = { [weak self](index:Int)->Void in
//            print("block select \(index)")
//            self?.popMenu = nil
//        }
        //show
        popMenu?.showOnTheView(spView: view)
        popMenu?.didSelectMenuBlock = { [weak self](index) in
            if let self = self{
                Vibrations.selection.vibrate()
                if 0 == index{
                    //测试运行
                    self.testRunAtIndex(indexPath: indexPath)
                }else if 1 == index{
                    //添加到App的当前桌面
                    self.addAppToAiDesk(indexPath: indexPath)
                }else if 2 == index{
                    //显示输入电话号码对话框
                    self.showInputTelNumDlg()
                }
            }
        }
    
    }
    
//MARK: - 输入测试电话号码
    func showInputTelNumDlg(){
        if telInputDlg != nil{
            telInputDlg?.removeFromSuperview()
            telInputDlg = nil
        }
        
        let backView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        view.addSubview(backView)
        backView.backgroundColor = .systemGroupedBackground.withAlphaComponent(0.25)

        telInputDlg = UIView(frame: CGRect(x: screen_W/2-150, y: -121, width: 300, height: 120))
        backView.addSubview(telInputDlg!)
        telInputDlg?.backgroundColor = prjTitleColor.withAlphaComponent(0.95)
        telInputDlg?.setShadow(shadowColor: prjTitleColor, offset: CGSize(width: 3, height: 3), opacity: 0.25, radius: 10)
//        telInputDlg?.layer.opacity = 0
        
        let labelTitle = UILabel(frame: CGRect(x: 30, y: 20, width: 300-60, height: 30))
        telInputDlg?.addSubview(labelTitle)
        labelTitle.text = "请输入要拨打的电话号码："
        labelTitle.font = .boldSystemFont(ofSize: 16)
        labelTitle.textColor = .secondaryLabel
        let edtInput = UITextField(frame: CGRect(x: 30, y: 50, width: 300-60, height: 36))
        telInputDlg?.addSubview(edtInput)
        edtInput.textColor = .label
        edtInput.font = .systemFont(ofSize: 14)
        edtInput.returnKeyType = .done
        edtInput.keyboardType = .numbersAndPunctuation
        edtInput.delegate = self
        edtInput.tag = 1002

        let line = CALayer()
        telInputDlg?.layer.addSublayer(line)
        line.backgroundColor = UIColor.separator.cgColor
        line.frame = CGRect(x: 30, y: 50+36, width: 300-60, height: 1)
        
        let btn = UIButton(frame: CGRect(x: 300-10-24, y: 10, width: 24, height: 24))
        telInputDlg?.addSubview(btn)
        btn.setImage(UIImage(named: "dlg_close_white@2x.png"), for: .normal)
        btn.addActionWithBlock { sender in
            edtInput.resignFirstResponder()
            self.closeInputTelNumDlg()
        }
        
        
        UIView.animate(withDuration: 0.25,delay: 0,options: [.curveEaseInOut]) {
//            self.telInputDlg?.layer.opacity = 1
            self.telInputDlg?.frame = CGRect(x: screen_W/2-150, y: screen_H/2 - 100, width: 300, height: 120)
        }
    }
    
    func closeInputTelNumDlg(){
        if self.telInputDlg != nil{
            UIView.animate(withDuration: 0.25) {
                self.telInputDlg?.layer.opacity = 0
            } completion: { flag in
                self.telInputDlg?.superview?.removeFromSuperview()
                self.telInputDlg?.removeFromSuperview()
                self.telInputDlg = nil
            }
        }
        
    }

//MARK: - 打开测试
    func testRunAtIndex(indexPath: IndexPath){
        if isSousuoPage{
            let iSec = indexPath.section
            if iSec<sousuoSource.count{
                let index = indexPath.row
                if index >= sousuoSource[iSec].count{
                    return
                }
                let content = sousuoSource[iSec][index]
                self.testRunWithCmd(content,self.telPhoneNum)
            }
        }else{
            let index = indexPath.row
            if index >= sourceList.count{
                return
            }
            let content = sourceList[index]
            self.testRunWithCmd(content,self.telPhoneNum)
        }
        
    }
    
//MARK: - 添加到Ai桌面
    func addAppToAiDesk(indexPath: IndexPath){
        if isSousuoPage{
            let iSec = indexPath.section
            if iSec<sousuoSource.count{
                let index = indexPath.row
                if index >= sousuoSource[iSec].count{
                    return
                }
                let content = sousuoSource[iSec][index]
                self.addAppToAiDesk(contentUrl: content)
            }
        }else{
            let appIndex = indexPath.row
            if appIndex >= sourceList.count{
                return
            }
            let content = sourceList[appIndex]
            self.addAppToAiDesk(contentUrl: content)
        }
        
    }
    
    func addAppToAiDesk(contentUrl:String){
        var content = contentUrl
        
        let arr = content.components(separatedBy: "&|&")
        if arr[0].hasPrefix("url=tel://%@"){
            if self.telPhoneNum != nil && !self.telPhoneNum!.isEmpty{
                content = "url=tel://" + self.telPhoneNum!
                for i in 1 ..< arr.count{
                    content.append("&|&"+arr[i])
                }
            }
        }else{
//非电话命令，保存原始Title，以便目标无法访问时，可以使用原始title进行搜索
//先判断如果是固定小程序功能
//alipay-支付宝，weixin-微信/dingtalk-钉钉/wxwork-企业微信/mqqapi-QQ/tim-TIM/openapp.jdmobile-京东/feishu-飞书
//App-Prefs更不需
            let urlkey = (arr[0] as NSString).substring(from: 4) as String
            if let _ = AiScreenFunc.getUrlschemeTitle(urlScheme: urlkey){
//已经有，则不管
            }else if arr.count>=3{
//没有则新增 //url=xxx[&path=xx][&|&storelink=xx]&|&title=xx&|&icon=xxx
                let title = (arr[arr.count-2] as NSString).substring(from: 6) as String
                if let data = UserDefaults.standard.value(forKey: "aiScreen.basic.title.forurl"){
                    if let dictData = data as? NSDictionary{
                        let mutiDict = NSMutableDictionary(dictionary: dictData)
                        mutiDict.setValue(title, forKey: urlkey)
                        UserDefaults.standard.setValue(NSDictionary(dictionary: mutiDict), forKey: "aiScreen.basic.title.forurl")
                        UserDefaults.standard.synchronize()
                    }
                }else{
                    let tmpDict = NSDictionary(object: title, forKey: urlkey as NSCopying)
                    UserDefaults.standard.setValue(tmpDict, forKey: "aiScreen.basic.title.forurl")
                    UserDefaults.standard.synchronize()
                }
            }
        }
        if let theSnapshot = self.view.snapshot2Image(){
            self.didCloseBlock?(theSnapshot)
        }
        self.dismiss(animated: false)
        didAddAppBlock?(content)
    }

}

extension AppendVC:UITableViewDelegate, UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if isSousuoPage{
            return self.sousuoSource.count
        }else{
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if isSousuoPage{
            return self.sousouTitles[section]
        }else{
            return ""
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if isSousuoPage{
            return 36
        }else{
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isSousuoPage{
            if self.sousuoSource.count>section{
                return self.sousuoSource[section].count
            }else{
                return 0
            }
        }else{
            return self.sourceList.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "AppendAppCell") as? AppendAppCell//从缓存池中取
        if nil == cell{//如缓存池中没取到，则创建
            cell = UITableViewCell.init(style: .default, reuseIdentifier: "AppendAppCell") as? AppendAppCell
        }
        if isSousuoPage{
            cell!.showTitle(title: self.sousuoSource[indexPath.section][indexPath.row])
        }else{
            cell!.showTitle(title: self.sourceList[indexPath.row])
        }
        cell!.didTapAddBlock = {[weak self] in //不用weakself会造成循环引用导致无法deinit
//点击添加,显示菜单
            if let self = self{
                Vibrations.medium.vibrate()
                let rect = tableView.convert(tableView.rectForRow(at: indexPath), to: self.view)//转成相对于屏幕的位置(主要取其Y坐标)
                self.showPopmenu(cellRect: rect,at: indexPath)
            }
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //直接点击为运行测试该项
        Vibrations.light.vibrate()
        self.testRunAtIndex(indexPath: indexPath)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
}


extension AppendVC :UITextFieldDelegate{
    //MARK: - UITextFieldDelegate
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            if 1001 == textField.tag{
//Appstore搜索
                let keyStr = textField.text
                if keyStr == nil || keyStr!.isEmpty {
                    return true
                }
                self.doSearch(keyword: keyStr!)
            }else if 1002 == textField.tag{
//设定拨打电话号码
                self.telPhoneNum = textField.text
                self.closeInputTelNumDlg()
            }
            return true
        }
}

//MARK: - 搜索关键词
extension AppendVC{
    func doSearch(keyword:String){
        func showSearchResult(_ message:String?){
            UserDefaults.standard.set(self.sousuoSource, forKey: "aiScreen.dCache.last.Append.sousuoList")
            UserDefaults.standard.set(self.sousouTitles, forKey: "aiScreen.dCache.last.Append.sousuoTitles")
            UserDefaults.standard.synchronize()
            DispatchQueue.main.async {
                loadingHud.hide(animated: true)
                if let msg = message{
                    self.view.showToast(msg)
                }
                self.showPage(ipage:self.tabItems.count-1) //定位到搜索列表
            }
        }
        self.sousuoSource.removeAll()
        self.sousouTitles.removeAll()
        var isNullResult = true
        //先启动loading动画
        let loadingHud = MBProgressHUD.showAdded(to: self.view, animated: true) //简单加载指示器也可以直接UIActivityIndicatorView来代替
        loadingHud.label.text = "搜索中,请稍候"
        
//先在本地列表搜索
        var localResult:[String] = []
        for ipage in 0 ..< jsonfiles.count{
            let jsonName = jsonfiles[ipage]
            let tmpResult = HLUniversalFunc.getArrFromJSONFile(forName: jsonName)
            for result in tmpResult {
                let tmpArr = result.components(separatedBy: "&|&") //如果是中文关键词，不需要做此处理，但英文关键词则就有必要了
                if tmpArr.count>=3{
                    let titleIndex = tmpArr.count-2
                    let title = tmpArr[titleIndex]
                    if title.lowercased().contains(keyword.lowercased()){
                        localResult.append(result)
                    }
                }
            }
        }
        let uniqueResult = localResult.uniqueFilter
        if uniqueResult.count>0{
            self.sousouTitles.append("列表搜索结果")
            self.sousuoSource.append(uniqueResult)
            isNullResult = false
        }else{
            self.sousouTitles.append("列表中没有找到")
            self.sousuoSource.append([])
        }
        
//eg:https://itunes.apple.com/search?term=时钟&country=CN&media=software
        let searchUrl = String(format: "https://itunes.apple.com/search?term=%@&country=CN&media=software", keyword)
        AFURLRequestManager.sharedInstance().getJsonData(searchUrl, withparam: nil) {[weak self] (jsonData, code) in
            guard let self = self else { return }
            
            if (jsonData != nil) && 200 == code{
//data解析,格式如下：
/*
 {
"resultCount": 50,
"results": [{"bundleId": "com.didapinche.taxi","trackName": "嘀嗒出行-顺风车出租车出行必用","trackId": 921478733,"artworkUrl100": "https://is2-ssl.mzstatic.com/image/thumb/Purple126/v4/99/f0/c4/99f0c4d5-cde9-2d00-0059-5214ccc088bf/AppIcon-1x_U007emarketing-0-7-0-0-85-220.png/100x100bb.jpg"},{}]
 //artworkUrl100为100*100的App图标，如果没有可以再判断下artworkUrl60有没有60*60的
 //https://apps.apple.com/app/totocloud/id921478733,可以跳转到下载页面
}
*/
                    let dict = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers)
                    if dict != nil {
                        let tmpDict = dict as! NSDictionary
                        if tmpDict["results"] is NSArray{
                            let tmpResult = tmpDict["results"] as? NSArray
                            if tmpResult != nil{
                                var storeResult:[String] = []
                                for i in 0 ..< tmpResult!.count{
                                    let perDict = tmpResult![i] as? NSDictionary
                                    if perDict != nil{
                                        let bundleId = perDict!["bundleId"] as? String
                                        let trackName = perDict!["trackName"] as? String
                                        let trackId = perDict!["trackId"] as? CLongLong
                                        var artworkUrl100 = perDict!["artworkUrl100"] as? String
                                        if artworkUrl100 == nil{
                                            artworkUrl100 = perDict!["artworkUrl60"] as? String
                                            if artworkUrl100 == nil{
                                                artworkUrl100 = perDict!["artworkUrl512"] as? String
                                            }
                                        }
//组成数据格式：url=xxx[&path=xx][&|&storelink=xx]&|&title=xx&|&icon=xxx
//如："url=hl://scheme2?u=com.ss.iphone.article.lite&|&title=今日头条极速版&|&icon=https://xxx/512x512bb.jpg"
                                        if bundleId != nil && trackName != nil && trackId != nil && artworkUrl100 != nil{
                                            let url = String(format: "hl://scheme2?u=%@", bundleId!)
                                            let storelink = String(format: "https://apps.apple.com/app/totocloud/id%ld", trackId!)
//                                            print("storelink:\(storelink)")
                                            let urlstr = String(format: "url=%@&|&storelink=%@&|&title=%@&|&icon=%@", url,storelink,trackName!,artworkUrl100!)
                                            storeResult.append(urlstr)
                                        }
                                    }
                                }
                                if storeResult.count>0{
                                    self.sousouTitles.append("AppStore搜索结果")
                                    self.sousuoSource.append(storeResult)
                                    isNullResult = false
                                }else{
                                    self.sousouTitles.append("AppStore中没有找到")
                                    self.sousuoSource.append([])
                                }
                                showSearchResult(isNullResult ? "未搜索到结果,请稍候重试..." : nil)
                                return
                            }
                        }
                    }
                showSearchResult(isNullResult ? "搜索到结果有误,请稍候重试..." : nil)
                }else{
                    showSearchResult(isNullResult ? "未搜索到结果[\(code)]" : nil)
                }
        }
        
    }
    
}


extension AppendVC{
//MARK: - 自定义快捷
    func selectAppLogo(){
        self.tapBackView()
        let iconVC = AppIconVC()
        self.present(iconVC, animated: true)
        iconVC.selectNewIcoBlock = { icoName in
            self.customLogoName = icoName
            self.customImgLogo?.setImageWithStr(imgurl: icoName,defName: defaultIcoLogo)
        }
    }
    
    func initCustomDefineView(){
        if customDefineView == nil{
            var workWidth = screen_W-50
            let backView = UIView(frame: CGRect(x: 0, y: 0, width: workWidth, height: workAreaView.bounds.height))
            workAreaView.addSubview(backView)
            self.customDefineView = backView
            
            var iTop = 15.0
            let iLeft = 10.0
            let workRowHeight = 48.0
            
            workWidth -= 2*iLeft
            
            let row_2 = UIView(frame: CGRect(x: iLeft, y: iTop, width: workWidth, height: workRowHeight*2))
            backView.addSubview(row_2)
            row_2.layer.cornerRadius = 10
            row_2.backgroundColor = .tertiarySystemGroupedBackground
            
            var titleWidth = 75.0
            let labelTitle = UILabel(frame: CGRect(x: iLeft, y: 0, width: titleWidth, height: workRowHeight))
            row_2.addSubview(labelTitle)
            labelTitle.text = "快捷名称:"
            labelTitle.textColor = .label
            labelTitle.font = .systemFont(ofSize: 16)
            
            let field_name = UITextField()
            row_2.addSubview(field_name)
            field_name.textAlignment = .right
            field_name.textColor = .label
            field_name.font = .systemFont(ofSize: 15)
            field_name.placeholder = "请输入名称"
            field_name.delegate = self
            field_name.clearButtonMode = .whileEditing
            field_name.returnKeyType = .done
            field_name.frame = CGRect(x: iLeft+titleWidth+10.0, y: workRowHeight/2-18, width: workWidth-titleWidth-40.0, height: 36)
            self.customFieldName = field_name
            
            let line_2 = CALayer()
            row_2.layer.addSublayer(line_2)
            line_2.frame = CGRect(x: iLeft, y: workRowHeight-0.5, width: workWidth-15, height: 0.5)
            line_2.backgroundColor = UIColor.separator.cgColor
            
            let labelIco = UILabel(frame: CGRect(x: iLeft, y: workRowHeight, width: workWidth-15-36-40, height: workRowHeight))
            row_2.addSubview(labelIco)
            labelIco.text = "选择快捷图标"
            labelIco.textColor = .label
            labelIco.font = .systemFont(ofSize: 16)
            
            let imgLogo = UIImageView()
            row_2.addSubview(imgLogo)
            imgLogo.frame = CGRect(x: workWidth-36-44, y: workRowHeight+workRowHeight/2-20, width: 40, height: 40)
            imgLogo.layer.cornerRadius = 6
            imgLogo.clipsToBounds = true
            customImgLogo = imgLogo
            customLogoName = "network.badge.shield.half.filled"
            customImgLogo?.setImageWithStr(imgurl: customLogoName!)
            
            let btnArrow = UIButton(frame: CGRect(x: workWidth-36, y: workRowHeight+workRowHeight/2-18, width: 36, height: 36))
            row_2.addSubview(btnArrow)
            btnArrow.setImage(UIImage(named: "arrowMore@2x.png"), for: .normal)
            btnArrow.addActionWithBlock { sender in
                self.selectAppLogo()
            }
            
            
            iTop += workRowHeight*2+10
            let row_1 = UIView(frame: CGRect(x: iLeft, y: iTop, width: workWidth, height: workRowHeight))
            backView.addSubview(row_1)
            row_1.layer.cornerRadius = 10
            row_1.backgroundColor = .tertiarySystemGroupedBackground
            iTop += workRowHeight

            titleWidth = 75.0
            let labelCmd = UILabel(frame: CGRect(x: iLeft, y: 0, width: titleWidth, height: workRowHeight))
            row_1.addSubview(labelCmd)
            labelCmd.text = "启动命令:"
            labelCmd.textColor = .label
            labelCmd.font = .systemFont(ofSize: 16)
//
            let field = UITextField()
            field.textColor = .label
            field.font = .systemFont(ofSize: 15)
            field.textAlignment = .right
            field.placeholder = "weixin://"
            field.delegate = self
            field.returnKeyType = .done
            field.clearButtonMode = .whileEditing
            row_1.addSubview(field)
            field.frame = CGRect(x: iLeft+titleWidth+10.0, y: workRowHeight/2-18, width: workWidth-titleWidth-40.0, height: 36)
            self.customFieldCmd = field
            
            iTop += 15
            workWidth = screen_W-50
            let hightTextColor = prjTitleColor
            let btn_save = UIButton(frame: CGRect(x: workWidth-10-100, y: iTop, width: 100, height: 36))
            backView.addSubview(btn_save)
            btn_save.setImage(UIImage(named: "menu_down@2x.png"), for: .normal)
            btn_save.setTitle(" 确定", for: .normal)
            btn_save.setTitleColor(hightTextColor, for: .normal)
            btn_save.titleLabel?.font = .systemFont(ofSize: 16)
            btn_save.addActionWithBlock { [weak self](sender) in
                if let self = self{
                    let strTitle = self.customFieldName?.text
                    if strTitle == nil  || strTitle!.isEmpty{
                        self.alertMessage("快捷名称不能为空", message: "请输入快捷启动的名称")
                        return
                    }
                    let strcmd = self.customFieldCmd?.text
                    if strcmd == nil  || strcmd!.isEmpty{
                        self.alertMessage("启动命令为空", message: "请按规则输入有效的启动命令")
                        return
                    }
                    let contentUrl = String(format: "url=%@&|&title=%@&|&icon=%@",
                                            strcmd!,
                                            strTitle!,
                                            self.customLogoName!)
                    self.addAppToAiDesk(contentUrl: contentUrl)
                }
            }
            
            let btn_test = UIButton(frame: CGRect(x: workWidth-10-100-15-80, y: iTop, width: 80, height: 36))
            backView.addSubview(btn_test)
            btn_test.setTitle("测试运行", for: .normal)
            btn_test.setTitleColor(hightTextColor, for: .normal)
            btn_test.titleLabel?.font = .systemFont(ofSize: 16)
            btn_test.addActionWithBlock { sender in
//须先判断
                let strcmd = self.customFieldCmd?.text
                if strcmd == nil  || strcmd!.isEmpty{
                    self.alertMessage("启动命令为空", message: "请按规则输入有效的启动命令")
                    return
                }
                let cmdUrl = String(format: "url=%@&|&title=%@&|&icon=%@",
                                    strcmd!,
                                    self.customFieldName!.text!,
                                    self.customLogoName!)
                self.testRunWithCmd(cmdUrl)
            }
            
            iTop += 36+20
            
//所要高亮的词组格式为：正则表达式
/*
 \s表示匹配任何空白字符：(包含空格、制表符、换页符，等价于\f\n\r\t\v),注意在swift字符串中，特殊字符本身也需要再加个\表示，故，下面pattern中用为"\\sweixin://\\s"
 \b匹配一个单词边界
 如果字符串里面本身含有?，则要用\?表示，在swift字符串则为\\?
 */
            
            let customType = ActiveType.custom(pattern: "\\sweixin://\\s")
            let customType2 = ActiveType.custom(pattern: "\\salipay://\\n")
            let customType3 = ActiveType.custom(pattern: "\\shl://scheme2\\?u=com.tencent.xin\\b")//hl://scheme2?u=
            let customType4 = ActiveType.custom(pattern: "\\stel://10086\\b")
            let customType5 = ActiveType.custom(pattern: "\\salipay://platformapi/startapp\\?saId=200011235\\b")
            let customType6 = ActiveType.custom(pattern: "\\sweixin://123456\\?userName=gh_2c8d4d5e2d8a\\b")
            let customType7 = ActiveType.custom(pattern: "\\s了解更多\\b")
            let customType8 = ActiveType.custom(pattern: "\\s启动命令填写规则如下:\\n")
            
            let label = ActiveLabel()
            label.enabledTypes.append(customType)
            label.enabledTypes.append(customType2)
            label.enabledTypes.append(customType3)
            label.enabledTypes.append(customType4)
            label.enabledTypes.append(customType5)
            label.enabledTypes.append(customType6)
            label.enabledTypes.append(customType7)
            label.enabledTypes.append(customType8)
            label.urlMaximumLength = 31
            label.customize { label in
                label.text = "      启动命令填写规则如下:" +
                "\n应用UrlScheme: weixin:// , alipay://" +
                "\n应用bid: hl://scheme2?u=com.tencent.xin" +
                "\n打电话: tel://10086" +
                "\n支付宝程序:\n alipay://platformapi/startapp?saId=200011235" +
                "\n微信小程序:\n weixin://123456?userName=gh_2c8d4d5e2d8a" +
                "\n网址: https://www.baidu.com" +
                "\n\n 了解更多"
                
                label.numberOfLines = 0
                label.lineSpacing = 4
                label.textColor = .secondaryLabel
                label.font = .systemFont(ofSize: 12)
                label.URLColor = .link
                label.URLSelectedColor = UIColor(red: 82.0/255, green: 190.0/255, blue: 41.0/255, alpha: 1)
                
                //Custom types
                label.customColor[customType] = hightTextColor
                label.customSelectedColor[customType] = UIColor.green
                label.customColor[customType2] = hightTextColor
                label.customSelectedColor[customType2] = UIColor.green
                label.customColor[customType3] = hightTextColor
                label.customSelectedColor[customType3] = UIColor.green
                label.customColor[customType4] = hightTextColor
                label.customSelectedColor[customType4] = UIColor.green
                label.customColor[customType5] = hightTextColor
                label.customSelectedColor[customType5] = UIColor.green
                label.customColor[customType6] = hightTextColor
                label.customSelectedColor[customType6] = UIColor.green
                label.customColor[customType7] = hightTextColor
                label.customSelectedColor[customType7] = UIColor.green
                label.customColor[customType8] = UIColor(hexString: "#f9ab23")
                
                label.handleURLTap {HLUniversalFunc.openSchemeUrl($0.absoluteString, nil) }
                label.handleCustomTap(for: customType) { HLUniversalFunc.openSchemeUrl($0, nil) }
                label.handleCustomTap(for: customType2) { HLUniversalFunc.openSchemeUrl($0, nil) }
                label.handleCustomTap(for: customType3) {
                    UIPasteboard.general.string = $0
                    HLUniversalFunc.openAppScheme($0,nil)
                }
                label.handleCustomTap(for: customType4) {
                    UIPasteboard.general.string = $0
                    HLUniversalFunc.openSchemeUrl($0, nil)
                }
                label.handleCustomTap(for: customType5) {
//小程序命令较长，点击的时候，顺带复制以便用户输入
                    UIPasteboard.general.string = $0
                    HLUniversalFunc.openSchemeUrl($0, nil)
                }
                label.handleCustomTap(for: customType6) {
                    UIPasteboard.general.string = $0
                    HLUniversalFunc.openSchemeUrl($0, nil)
                }
                //打开官网.need.do.replace
                label.handleCustomTap(for: customType7) { _ in HLUniversalFunc.openSchemeUrl("https://www.jianshu.com/p/3525db6ae60b?v=1695796158990", nil) }
            }
            label.frame = CGRect(x: 10, y: iTop, width: workWidth-20, height: 200)
            backView.addSubview(label)
            
            let imgview = UIImageView(image: UIImage(named: "img_alert@2x.png"))
            label.addSubview(imgview)
            imgview.frame = CGRect(x: 0, y: 0, width: 16, height: 16)
            
        }else{
            customDefineView?.isHidden = false
        }
        
    }
}

